<template>
  <div class="main">
    <mine-title>{{ this.title }}</mine-title>
    <div class="content" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="12">
          <div>
            <el-form
              ref="form"
              :model="form"
              label-width="110px"
              :rules="rules"
            >
              <el-form-item label="算法编码：" prop="algoCode">
                <el-input
                  v-model="form.algoCode"
                  size="small"
                  clearable
                  style="width: 512px"
                ></el-input>
              </el-form-item>
              <el-form-item label="算法名称：" prop="algoName">
                <el-input
                  v-model="form.algoName"
                  size="small"
                  clearable
                  style="width: 512px"
                ></el-input>
              </el-form-item>
              <el-form-item label="算法类型：" prop="algoType">
                <el-select
                  v-model="form.algoType"
                  placeholder="请选择"
                  style="width: 512px"
                >
                  <el-option
                    v-for="item in algoTypeSelection"
                    :key="item.optCode"
                    :label="item.optName"
                    :value="item.optCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="实现功能：" prop="purpose">
                <el-input
                  type="textarea"
                  v-model="form.purpose"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  style="width: 512px"
                ></el-input>
              </el-form-item>
              <el-form-item label="算法原理：" prop="algoTheory">
                <el-input
                  type="textarea"
                  v-model="form.algoTheory"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  style="width: 512px"
                ></el-input>
              </el-form-item>
              <el-form-item label="结果说明：" prop="resultDesc">
                <el-input
                  type="textarea"
                  v-model="form.resultDesc"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  style="width: 512px"
                ></el-input>
              </el-form-item>

              <!-- <el-form-item label="算法语言：" prop="language">
                <el-input
                  v-model="form.language"
                  size="small"
                  clearable
                  style="width: 512px"
                ></el-input>
              </el-form-item> -->

              <el-form-item label="备注：" prop="remarks">
                <el-input
                  type="textarea"
                  v-model="form.remarks"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  style="width: 512px"
                ></el-input>
              </el-form-item>
              <el-form-item label="上传数据：" prop="file">
                <mine-upload
                  ref="upload"
                  :fileType="accept"
                  @change="onChange"
                  :fileList="fileList"
                ></mine-upload>
              </el-form-item>
              <el-form-item label="高校测试模型：" prop="modelCode">
                <el-select
                  v-model="form.modelCode"
                  placeholder="请选择"
                  style="width: 512px"
                >
                  <el-option
                    v-for="item in modelSelection"
                    :key="item.optCode"
                    :label="item.optName"
                    :value="item.optCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="排序码：" prop="sort">
                <el-input-number v-model="form.sort" autosize></el-input-number>
              </el-form-item>

              <el-form-item class="form-btn-row">
                <mine-button type="primary" @click="onCancel" secondary
                  >取 消
                </mine-button>
                <mine-button type="primary" @click="onSubmit"
                  >保 存
                </mine-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import request from "@/modules/index/utils/request";
import qs from "qs";
import dictAdmin from "../../../store/modules/dictAdmin";

export default {
  name: "addDict",
  data() {
    return {
      title: "",
      path: "/code/list",
      form: {
        creater: "",
        algoName: "",
        language: "",
        counts: "",
        createTime: "",
        purpose: "",
        remarks: "",
        id: 0,
        number: 0,
        file: null,
        modelCode: "",
      },
      rules: {
        algoName: [
          { required: true, message: "请填写算法名称", trigger: "blur" },
        ],
        language: [
          { required: false, message: "请填写算法语言", trigger: "blur" },
        ],
      },
      loading: false,
      modelSelection: [], // 高校测试模型下拉选项
      algoTypeSelection: [], // 算法类型下拉选项
      fileList: [], // 文件上传的数据
    };
  },
  watch: {
    "$route.query": {
      immediate: true,
      handler(val) {
        // 给排序码赋值
        this.form.sort = ++val.detectTotal;
        // 如果是编辑页面，先做页面数据的回显
        if (val.isEdit) {
          // if (this.$store.state.codeDetect.detectListRowData.testFileName) {
          //   this.fileList.push({
          //     name: this.$store.state.codeDetect.detectListRowData.testFileName,
          //   }); // 文件上传的回显
          // }
          this.form = this.$store.state.codeDetect.detectListRowData;
          if (this.form.testFileName) {
            this.fileList = [{ name: this.form.testFileName }];
          }
        }
      },
    },
  },
  computed: {
    accept() {
      return ".txt,.xls,.xlsx";
    },
  },
  methods: {
    async getModelSelection() {
      let params = {
        dirCode: "test_model_type",
      };
      if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/dictionary/TreeList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.modelSelection = res?.data[0].childrenParams;
            } else {
              this.$message.error("获取函数数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getDicBydirCode", params);
        if (res.data.status === 200) {
          this.modelSelection = res.data?.data[0].childrenParams;
        } else {
          this.$message.error("获取函数数据失败");
        }
      }
    },
    async getAlgoTypeSelection() {
      let params = {
        dirCode: "algo_type",
      };
      if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/dictionary/TreeList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.algoTypeSelection = res?.data[0].childrenParams;
            } else {
              this.$message.error("获取函数数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getDicBydirCode", params);
        if (res.data.status === 200) {
          this.algoTypeSelection = res.data?.data[0].childrenParams;
        } else {
          this.$message.error("获取函数数据失败");
        }
      }
    },
    onChange(data, fileList) {
      this.form.file = data.file;
    },
    onSubmit() {
      let _this = this;
      this.$refs.form.validate(async (valid, object) => {
        let { form } = _this;
        form.type = 1;
        let formData = new FormData();
        formData.append("file", this.form?.file?.raw);
        if (valid) {
          this.loading = true;
          //   判断是新增还是编辑
          if (this.$route.query.isEdit) {
            if (this.$webview2.isWPF) {
              const uuid = this.$webview2.generateRandomUUID();
              await this.$webview2.sendWebView2(
                `/algoTemplateFile/updateAll?${qs.stringify(form, {
                  indices: false,
                })}`,
                "post",
                "application/json;charset=UTF-8",
                formData,
                false,
                uuid
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  let res = e.data.response;
                  // TODO： 定制后台数据处理
                  if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                    this.$confirm("保存成功，是否需要返回列表？", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    })
                      .then(() => {
                        if (this.$route.query.isCut) {
                          this.$router.push("/code/shortcut");
                        } else {
                          this.$router.push(this.path);
                        }
                      })
                      .catch(() => {
                        this.loading = false;
                      });
                  } else {
                    this.loading = false;
                    this.$message.error(res.msg || "编辑失败");
                    return;
                  }
                },
                { once: true }
              );
            } else {
              request({
                url: `/algoTemplateFile/updateAll?${qs.stringify(form, {
                  indices: false,
                })}`, //接口
                method: "post",
                data: formData,
              }).then((response) => {
                let result = response.data;
                if (!result.success) {
                  this.loading = false;
                  this.$message.error(result.msg || "编辑失败");
                  return;
                }
                this.$confirm("保存成功，是否需要返回列表？", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.$router.push(this.path);
                  })
                  .catch(() => {
                    this.loading = false;
                  });
              });
            }
          } else {
            if (this.$webview2.isWPF) {
              await this.$webview2.sendWebView2(
                `/algoTemplateFile/save?${qs.stringify(form, {
                  indices: false,
                })}`,
                "post",
                "application/json;charset=UTF-8",
                {},
                false
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  let res = e.data.response;
                  // TODO： 定制后台数据处理
                  if (res.status === 200) {
                    this.$confirm("保存成功，是否需要返回列表？", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    })
                      .then(() => {
                        this.$router.push(this.path);
                        this.$message.success(res.msg || "新建失败");
                        // if (!this.$route.query.isCut) {
                        //     !this.$route.query.isPredict ? this.$router.push("/code/list") : this.$router.push("/code/predictList");
                        // } else {
                        //     !this.$route.query.isPredict ? this.$router.push("/code/shortcut") : this.$router.push("/code/previewCodeCut");
                        // }
                      })
                      .catch(() => {});
                  } else {
                    this.loading = false;
                    this.$message.error(res.msg || "新建失败");
                    return;
                  }
                },
                { once: true }
              );
            } else {
              request({
                url: `/algoTemplateFile/save?${qs.stringify(form, {
                  indices: false,
                })}`,
                method: "post",
                data: formData,
              }).then((response) => {
                let result = response.data;
                if (!result.success) {
                  this.loading = false;
                  this.$message.error(result.msg || "新建失败");
                  return;
                }
                this.$confirm("保存成功，是否需要返回列表？", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.$router.push(this.path);
                    // if (!this.$route.query.isCut) {
                    //     !this.$route.query.isPredict ? this.$router.push("/code/list") : this.$router.push("/code/predictList");
                    // } else {
                    //     !this.$route.query.isPredict ? this.$router.push("/code/shortcut") : this.$router.push("/code/previewCodeCut");
                    // }
                  })
                  .catch(() => {});
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.form = {
        creater: "",
        algoName: "",
        language: "",
        id: 0,
        purpose: "0",
        // number: 0,
      };
      this.$router.push(this.path);
      // if (!this.$route.query.isCut) {
      //     !this.$route.query.isPredict ? this.$router.push("/code/list") : this.$router.push("/code/predictList");
      // } else {
      //     !this.$route.query.isPredict ? this.$router.push("/code/shortcut") : this.$router.push("/code/previewCodeCut");
      // }
    },
  },
  created() {
    // 获取高校测试模型下拉选项
    this.getModelSelection();
    setTimeout(() => {
      this.getAlgoTypeSelection();
    }, 200);
    // if (!this.$route.query.isCut) {
    //   !this.$route.query.isPredict
    //     ? (this.title = "经典算法诊断")
    //     : (this.title = "经典算法预测");
    //   !this.$route.query.isPredict
    //     ? (this.path = "/code/list")
    //     : (this.path = "/code/predictList");
    // } else {
    //   !this.$route.query.isPredict
    //     ? (this.title = "经典算法诊断")
    //     : (this.title = "经典算法预测");
    //   !this.$route.query.isPredict
    //     ? (this.path = "/code/shortcut")
    //     : (this.path = "/code/previewCodeCut");
    // }
    // this.form.number = ++this.$store.state.dictAdmin.dictNumber;
    if (this.$route.query.isEdit) {
      this.$store.commit("SET_BREADCRUMB", [
        { title: "诊断算法模板", path: "/code/predictList" },
        { title: "编辑", path: "" },
      ]);
    } else {
      this.$store.commit("SET_BREADCRUMB", [
        { title: "诊断算法模板", path: "/code/predictList" },
        { title: "新增", path: "" },
      ]);
    }
  },
};
</script>

<style scoped>
</style>
